package top.yunmouren.areamusic.event;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import top.yunmouren.areamusic.AreaMusic;
import top.yunmouren.areamusic.commannd.PlayerSelectionCache;
import top.yunmouren.areamusic.config.AreaDto;

public class PlayerInteractBlockListener implements Listener {
    private final AreaMusic plugin;

    public PlayerInteractBlockListener(AreaMusic plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onEvent(PlayerInteractEvent event) {
        if (event.getClickedBlock() != null && event.getClickedBlock().getType() != Material.AIR) {
            ItemStack itemStack = event.getPlayer().getInventory().getItemInMainHand();
            ItemMeta itemMeta = itemStack.getItemMeta();
            if (itemMeta != null) {
                if (itemMeta.getLore() != null && itemMeta.getLore().size() == 1) {
                    String flag = (String)itemMeta.getLore().get(0);
                    if (flag.equals("§aAreaMusic §3选择工具")) {
                        PlayerSelectionCache.CreateAreaDto cache = this.plugin.getPlayerSelectionCache().getPlayerHistory(event.getPlayer().getUniqueId().toString());
                        if (cache != null) {
                            this.setLocation(event, cache, event.getClickedBlock().getLocation(), event.getAction() == Action.LEFT_CLICK_BLOCK);
                            event.setCancelled(true);
                        }
                    }
                }
            }
        }
    }

    private void setLocation(PlayerInteractEvent event, PlayerSelectionCache.CreateAreaDto createAreaDto, Location location, boolean first) {
        AreaDto.Point point = new AreaDto.Point(location.getX(), location.getY(), location.getZ());
        World world = location.getWorld();
        if (world != null) {
            createAreaDto.setWorld(world.getName());
        }

        if (first) {
            createAreaDto.setMinPoint(point);
            event.getPlayer().sendMessage("§6设置了第一个点");
        } else {
            createAreaDto.setMaxPoint(point);
            event.getPlayer().sendMessage("§e设置了第二个点");
        }

    }
}
